import { DatePicker, Input, InputNumber, Select } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import { CrudFormLayout } from '@/components/Crud';
import { DriverSelect, VehicleSelect } from '@/components/CustomForm';
import ImageUpload from '@/components/ImageUpload';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { useAsyncEffect } from 'ahooks';
import { Form, message } from 'antd';
import dayjs from 'dayjs';
import styles from './index.less';

const TIME_FIELDS = ['fromTime', 'toTime'];

const Save = (props) => {
  const { open, record, onCancel, onOk } = props;
  const [form] = Form.useForm();

  useAsyncEffect(() => {
    if (record) {
      const formData = {
        ...record,
        day: dayjs(record.day),
        images: record.images ? [{ url: record.images }] : [],
        transferLogs: record.transferLogs ? [{ url: record.transferLogs }] : [],
      };
      form?.setFieldsValue(formData);
    }
  }, [record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const url = record ? '/datas/expense/update' : '/datas/expense/add';
    const params = {
      ...values,
      day: values.day.format('YYYY-MM-DD'),
    };
    if (values.images && values.images.length) {
      params.images = values.images[0].url;
    } else {
      params.images = '';
    }
    if (values.transferLogs && values.transferLogs.length) {
      params.transferLogs = values.transferLogs[0].url;
    } else {
      params.transferLogs = '';
    }
    if (record) {
      params.expenseId = record?.expenseId;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };

  return (
    <CommonDrawer
      title={record ? '编辑报销单' : '新建报销单'}
      open={true}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={1000}
      destroyOnHidden
    >
      <Form form={form} layout="vertical" style={{ height: '100%' }}>
        <div className={styles.container}>
          <div className={styles.left}>
            <Form.Item label="报销凭证" name="images">
              <ImageUpload maxCount={1} />
            </Form.Item>
            <Form.Item label="付款凭证" name="transferLogs">
              <ImageUpload maxCount={1} />
            </Form.Item>
          </div>
          <div className={styles.right}>
            <CrudFormLayout itemMinWidth={180}>
              <Form.Item
                label="日期"
                name="day"
                rules={[REQUIRED]}
                initialValue={dayjs()}
              >
                <DatePicker needConfirm={false} placeholder="请选择日期" />
              </Form.Item>
              <Form.Item label="车辆" name="vehicleId" rules={[REQUIRED]}>
                <VehicleSelect
                  placeholder="请选择车辆"
                  onChange={(val, option) => {
                    try {
                      const driver = JSON.parse(option.drivers)?.[0];
                      if (driver) {
                        form.setFieldsValue({
                          driverId: driver?.driverId,
                          realname: driver?.realname,
                        });
                      }
                    } catch (error) {}
                  }}
                />
              </Form.Item>
              <Form.Item label="司机" name="driverId">
                <DriverSelect placeholder="请选择司机" />
              </Form.Item>
              <Form.Item label="费用类型" name="type" rules={[REQUIRED]}>
                <Select placeholder="请选择费用类型">
                  <Select.Option value={0}>路桥费</Select.Option>
                  <Select.Option value={1}>装卸车费</Select.Option>
                  <Select.Option value={2}>充电费</Select.Option>
                  <Select.Option value={3}>交警罚款</Select.Option>
                  <Select.Option value={4}>轮胎费</Select.Option>
                  <Select.Option value={5}>维修费</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item
                label="费用（元）"
                name="price"
                rules={[REQUIRED]}
                initialValue={0}
              >
                <InputNumber min={0} placeholder="请输入费用" />
              </Form.Item>
              <Form.Item label="付款帐号" name="account">
                <Input />
              </Form.Item>
            </CrudFormLayout>
            <CrudFormLayout>
              <Form.Item label="报销描述" name="msgs">
                <Input.TextArea maxLength={150} rows={3} />
              </Form.Item>
            </CrudFormLayout>

            <Form.Item label="备注" name="remark">
              <Input.TextArea maxLength={150} rows={3} />
            </Form.Item>
          </div>
        </div>
      </Form>
    </CommonDrawer>
  );
};

export default Save;
